package MusicPathdeal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import list.MusicList;
import model.Music;

public class MusicLeadin {
	private static String path = System.getProperty("user.dir")+"\\music\\music.txt";
	public static void writePath() throws IOException {
		// 将歌曲文件路径记录
		ArrayList<String> list = new ArrayList<>();
		Clear();
		for(int i=0;i<MusicList.getList().size();i++) {
			list.add(MusicList.getList().get(i).getId()+",,"+MusicList.getList().get(i).getName()+",,"+MusicList.getList().get(i).getPath());
		}
		FileOutputStream fos = new FileOutputStream(path);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(list);
		oos.close();
	}

	
	public static void readmusic() throws ClassNotFoundException, IOException {
		File f = new File(path);
		ArrayList<Music> List=MusicList.getList();
		if (!f.exists() || f.length() == 0) {
			System.out.println("文件为空！");
		} else {
			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream ois = new ObjectInputStream(fis);
			ArrayList<String> list = (ArrayList<String>) ois.readObject();
			ois.close();
			for(int i=0; i<list.size(); i++) {
			 String[] chars = list.get(i).split(",,"); 
			 Music music= new Music();
			 music.setId(chars[0]);
			 music.setName(chars[1]);
			 music.setPath(chars[2]);
			 List.add(music);
			}
		}
	}
	
	
	  public static void  Clear(){
		  File filename = new File(path); // 输入要删除的文件位置
			if(filename.exists())
				filename.delete();
	  }
	
}
